#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <cstdio>
#include <sys/time.h>
#include <stddef.h>

unsigned short Nvar1_seed[3] = {4,7,2};
unsigned short Nvar2_seed[3] = {5,8,1};
unsigned short Nvar3_seed[3] = {9,6,3};

double *trials;

int _M; // numero de iterações

int _N; // numero de threads

double Normal(float mean, float std)
{
    double var_u1, var_u2, var_u3;
    double x, tmp_val;
    
    var_u1 = erand48(Nvar1_seed);
    var_u2 = erand48(Nvar2_seed);
    x = -log(var_u1);
    tmp_val = exp(-((x - 1)*(x - 1)) / 2);
    while(var_u2 > tmp_val)
    {
        var_u1 = erand48(Nvar1_seed);
        var_u2 = erand48(Nvar2_seed);
        x = -log(var_u1);
        tmp_val = exp(-((x - 1)*(x - 1)) / 2);
    }
    var_u3 = erand48(Nvar3_seed);
    if(var_u3 > 0.5)
        return(mean + (std * x));
    else
        return(mean - (std * x));
}

typedef struct
{
    float S;
    float E;
    float R;
    float SIGMA;
    float T;
} thread_args;

double max(double a, double b)
{
    return a > b ? a : b;
}

void* blackScholes_run(thread_args arg)
{
    double t;
    
    for(int i=0; i < _M; i++)
    {
        t = arg.S * expl((arg.R - 0.5 * arg.SIGMA * arg.SIGMA) * arg.T + arg.SIGMA * sqrt(arg.T) * Normal(0,1));
        trials[i] = expl((-arg.R) * arg.T) *  max(t - arg.E, 0);
    }
    return NULL;
}

int main(int argc, const char * argv[])
{
    int i;
    double mean, stddev, confwidth, confmin, confmax;
    long long sum_x = 0, sum_x2 = 0;
    
    thread_args args;
    
    scanf("%f", &(args.S));
    scanf("%f", &(args.E));
    scanf("%f", &(args.R));
    scanf("%f", &(args.SIGMA));
    scanf("%f", &(args.T));
    scanf("%d", &_M);
    
    trials = (double*) malloc(_M * sizeof(double));
    
    blackScholes_run(args);
    
    for(i=0;i< _M;i++)
    {
        sum_x += trials[i];
        sum_x2 += trials[i] * trials[i];
    }
    mean = sum_x/_M;
    stddev = sqrt(sum_x2/_M - mean * mean);
    confwidth = 1.96f * stddev/sqrt(_M);
    confmin = mean - confwidth;
    confmax = mean + confwidth;
    
    printf("S        %.0lf\n", args.S);
    printf("E        %.0lf\n", args.E);
    printf("r        %.0lf\n", args.R);
    printf("sigma    %.0lf\n", args.SIGMA);
    printf("T        %.0lf\n", args.T);
    printf("M        %d\n", _M);
    printf("Confidence interval: (%.4lf, %.4lf)\n", confmin, confmax);
    
    return 0;
}

